import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
  HttpResponse,
} from '@angular/common/http';
import { catchError, Observable, retry, tap, throwError } from 'rxjs';
import { LoadingService } from 'ng-devui';
import { AuthGuardService } from './@core/auth-guard-service.guard';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';

@Injectable()
export class ApiRequestInterceptor implements HttpInterceptor {
  whiteList = ['v1/user/captcha'];
  showLoading: any;

  constructor(
    private loadingService: LoadingService,
    private authGuardService: AuthGuardService,
    private router: Router,
    private cookieService: CookieService
  ) { }

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    let req = request;
    this.showLoading = this.loadingService.open();
    if (this.whiteList.indexOf(request.url) === -1) {
      req = request.clone({
        setHeaders: {
          token: this.cookieService.get('token')
        },
      });
    }

    return next.handle(req).pipe(
      retry(2),
      tap(
        (res: HttpEvent<any>) => {
          this.showLoading.loadingInstance.close();
          if (res instanceof HttpResponse) {
            if (res.headers.get('newtoken') && res.headers.get('tokenexpiredtime')) {
              var time = new Date(parseInt(res.headers.get('tokenexpiredtime')))
              this.cookieService.set('token', res.headers.get('newtoken'), time);
              localStorage.setItem('token', res.headers.get('newtoken'));
            }
          }
        },
        (err: any) => {
          if (err instanceof HttpErrorResponse) {
            this.showLoading.loadingInstance.close();
            if (location.href.includes('home') && err.status === 401) {
              this.cookieService.delete('token')
              localStorage.removeItem('token');
              return false;
            }
            this.authGuardService.showModalPanel(
              'warning',
              this.authGuardService.getErrorCode('' + err.status)
            );
            if (err.status == 401) {
              this.router.navigate(['login/logins']);
            }
          }
        }
      ),
      catchError((error: HttpErrorResponse) => throwError(error))
    );
  }
}
